package com.aube.plugin.gallery.preview;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.Response;
import com.android.volley.toolbox.Scheme;
import com.aube.plugin.gallery.PictureImp;
import com.aube.plugin.gallery.R;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.CanCloseLayout;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.imgcompress.Luban;
import com.huyn.baseframework.imgcompress.OnCompressListener;
import com.huyn.baseframework.model.AppShare;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.share.WeiboUtil;
import com.huyn.baseframework.share.WxUtil;
import com.huyn.baseframework.utils.StorageUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by panwankun on 2016/1/21.
 */
public class GalleryPreviewLayout extends DLLayout implements ImgPreviewVPAdapter.IPreviewPresenter, CanCloseLayout {

    protected ArrayList<ViewPicture> pictureList = new ArrayList<>();  //图片列表
    protected final int ANIM_DELAY = 300;
    private boolean animOn = false;
    protected ImgPreviewVPAdapter bigImgAdapter;
    protected MyViewPager mImgBig;
    private View mMask;
    private RelativeLayout root;
    private ImageView mWalaImgBig;
    private View mToolTop, mToolBottom;

    public View mShareLayout, mShareWechat, mShareWeibo, mShareTimeline;

    protected Bitmap  originBitmap;
    protected int originIndex = 0;
    private ViewPicture originPicture;
    
    private Handler mHandler = new Handler();

    private PictureDetailPresenter mPictureDetailPresenter;

    private OnLoadMoreListener mLoadMoreListener;

    /**
     * login
     */
    private RelativeLayout mLoginRoot;
    private ImageView mImgWechat, mImgWeibo, mImgClose;
    private View mLoginWeibo, mLoginWechat, mLoginDialog;
    private BlurViewDecorator mLoginBlur;

    public GalleryPreviewLayout(Context context) {
        this(context, null);
    }

    public GalleryPreviewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GalleryPreviewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {
        inflate(R.layout.gallery_preview, this, true);

        findAndInitView();

        mPictureDetailPresenter = new PictureDetailPresenter(context);
        mPictureDetailPresenter.init(getResources(), this, new PictureDetailPresenter.OnPresenter() {
            @Override
            public Bitmap onLoadBitmap(int res) {
                return BitmapFactory.decodeResource(getResources(), res);
            }

            @Override
            public void onHttpRequest(HashMap<String, String> params, Class clazz, String tag, Response.Listener listener) {
                if(mBridge != null)
                    mBridge.exeHttpRequest(params, clazz, tag, listener);
            }

            @Override
            public void onOpenShareLayout() {
                manageShareLayout(true);
            }

            @Override
            public View getBlurView() {
                return mImgBig;
            }

            @Override
            public int getThemeColor() {
                return getResources().getColor(R.color.theme);
            }

            @Override
            public String getType() {
                return "photo";
            }

            @Override
            public boolean checkLogin() {
//                if(mBridge != null) {
//                    return mBridge.isUserLogin();
//                }
                Utils.sysout("----------------check login");
                if(!UserUtil.isUserLogin()) {
                    showLoginLayout();
                    return false;
                }
                return true;
            }
        });

        initLoginLayout();
    }

    private static final int ANIM_DURATION = 400;
    private void showLoginLayout() {
        mLoginRoot.setAlpha(0f);
        mLoginRoot.setVisibility(View.VISIBLE);

        ObjectAnimator anim = ObjectAnimator.ofFloat(mLoginRoot, "alpha", 0f, 1f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mLoginBlur.invalidate();
            }
        });
        anim.setDuration(ANIM_DURATION);

        ValueAnimator valueAnim = ValueAnimator.ofFloat(0f, 1.2f, 1f);
        valueAnim.setDuration(ANIM_DURATION);
        valueAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mLoginDialog.setScaleX(value);
                mLoginDialog.setScaleY(value);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(anim, valueAnim);
        mSet.start();
    }

    private void dismiss() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(mLoginRoot, "alpha", 1f, 0f);
        anim.setDuration(ANIM_DURATION);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mLoginBlur.invalidate();
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginRoot.setVisibility(View.GONE);
            }
        });

        ValueAnimator valueAnim = ValueAnimator.ofFloat(1f, 1.2f, 0f);
        valueAnim.setDuration(ANIM_DURATION);
        valueAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mLoginDialog.setScaleX(value);
                mLoginDialog.setScaleY(value);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(anim, valueAnim);
        mSet.start();
    }

    public boolean dismissLayout() {
        if(mLoginRoot == null)
            return false;
        if(mLoginRoot.getVisibility() == View.VISIBLE) {
            dismiss();
            return true;
        }
        return false;
    }

    private void initLoginLayout() {
        mLoginRoot = (RelativeLayout) findViewById(R.id.login_layout);
        mLoginRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mLoginDialog = findViewById(R.id.dialog_layout);

        mLoginWeibo = findViewById(R.id.login_weibo);
        mLoginWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(mBridge != null)
                        mBridge.loginByChannel(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismiss();
            }
        });

        mLoginWechat = findViewById(R.id.login_wechat);
        mLoginWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    try {
                        WxUtil.wxLoginRequest(context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                dismiss();
            }
        });

        mImgClose = (ImageView) findViewById(R.id.dialog_flow_close);
        mImgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mImgWechat = (ImageView) findViewById(R.id.login_wechat_img);
        mImgWeibo = (ImageView) findViewById(R.id.login_weibo_img);

        mImgClose.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_close));
        mImgWechat.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_wechat_white));
        mImgWeibo.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_weibo_white));
//        mLoginDialog.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.card_bg)));

        GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{0x66000000, 0x66000000});
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        drawable.setCornerRadius(4);
        drawable.setStroke(1, 0xcd5f5f5f);
        mLoginDialog.setBackgroundDrawable(drawable);

        try {
//            Class<? extends BlurViewDecorator> clazz = context.getClassLoader().loadClass("com.aube.views.BlurringView").asSubclass(BlurViewDecorator.class);
//
//            Constructor<? extends BlurViewDecorator> constructor = clazz.getConstructor(Context.class);
//
//            mLoginBlur = constructor.newInstance(context);
//            mLoginBlur.setOverlayColor(0xcc202020);
//            mLoginBlur.setBlurredView(mImgBig);
            mLoginBlur = BlurViewDecorator.createBlurView(context, true);
            mLoginBlur.setOverlayColor(0xcc202020);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mLoginRoot.addView(mLoginBlur, 0, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void registLoadListener(OnLoadMoreListener listener) {
        mLoadMoreListener = listener;
    }

    public void appendData(List<PictureImp> mContent) {
        List<ViewPicture> list = ImagePreviewActivityHelper.toPictures(mContent);
        if(list != null && list.size() > 0) {
            if(pictureList != null)
                pictureList.addAll(list);
            List<String> resList = new ArrayList<>();
            for(ViewPicture vp : list)
                resList.add(vp.getPictureUrl());
            bigImgAdapter.append(resList);
        }
    }

    @Override
    public void fillData(Object o) {
    }

    public void showPreview(ArrayList<ViewPicture> list, int index) {
        originBitmap = OriginBitmapHelper.getInstance().getOriginBitmap();

        pictureList = list;
        originIndex = index >= 0 ? index : 0;

        setVisibility(VISIBLE);
        if (pictureList != null && originIndex < pictureList.size()){
            originPicture = pictureList.get(originIndex);
            if(originPicture.viewHeight > 0 && originPicture.viewWidth > 0)
                mHandler.post(new Runnable() {
                @Override
                public void run() {
                    BigIn();
                }
            });
            else
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        alphaShow();
                    }
                });
        }else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    alphaShow();
                }
            });
        }
    }

    private void findAndInitView() {
        root = (RelativeLayout) findViewById(R.id.preview_root);
        mMask = findViewById(R.id.big_iamge_mask);
        mImgBig = new MyViewPager(getContext());
        root.addView(mImgBig, 1, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mImgBig.setVisibility(View.GONE);
        mWalaImgBig = (ImageView) findViewById(R.id.big_image_img);

        mImgBig.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                updatePictureDetail(pictureList.get(i));

                Utils.sysout("----------------check if need load more");
                if(bigImgAdapter != null && mLoadMoreListener != null) {
                    int count = bigImgAdapter.getCount();
                    Utils.sysout("----------------" + i + "/" + count);
                    if (i >= count - 3) {
                        mLoadMoreListener.shouldLoadMore();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        mToolTop = findViewById(R.id.preview_top_funtion);
        mToolBottom = findViewById(R.id.preview_bottom_funtion);

        int statusHeight = SysUtil.getStatusHeight(getContext());
        if(statusHeight > 0) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mToolTop.getLayoutParams();
            params.setMargins(0, statusHeight, 0, 0);
        }

        ImageView saveBtn = (ImageView) findViewById(R.id.preview_save);
        saveBtn.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_save));
        ImageView closebtn = (ImageView) findViewById(R.id.preview_close);
        closebtn.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_close_preview));

        mShareLayout = findViewById(R.id.share_layout);
        mShareWechat = findViewById(R.id.share_wechat);
        mShareTimeline = findViewById(R.id.share_timeline);
        mShareWeibo = findViewById(R.id.share_weibo);

        ImageView mShareWechatImg = (ImageView) findViewById(R.id.share_img_wechat);
        ImageView mShareWeiboImg = (ImageView) findViewById(R.id.share_img_weibo);
        ImageView mShareTimelineImg = (ImageView) findViewById(R.id.share_img_pyq);
        mShareWechatImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_wechat));
        mShareWeiboImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_weibo));
        mShareTimelineImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_pyq));

        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
            }
        });

        mShareWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startShare(getCurrentUrl(), false);
                manageShareLayout(false);
            }
        });

        mShareTimeline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startShare(getCurrentUrl(), true);
                manageShareLayout(false);
            }
        });

        mShareWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareByWeibo();
                manageShareLayout(false);
            }
        });

        closebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mPictureDetailPresenter != null)
                    mPictureDetailPresenter.onDestroy();
                BigOut();
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePic();
            }
        });
    }

    private void updatePictureDetail(PictureImp picture) {
        mPictureDetailPresenter.update(picture);
    }

    protected void BigIn() {
        if (animOn)
            return;
        animOn = true;
        root.setVisibility(View.VISIBLE);

        mToolBottom.setAlpha(0f);

        float hwScale = 0.0f;
        if (pictureList.get(originIndex).getWidth() != 0) {
            hwScale = (float) pictureList.get(originIndex).getHeight() / (float) pictureList.get(originIndex).getWidth();
        }

        if (hwScale < 0.001f || originBitmap == null) {
            alphaShow();
            return;
        }

        List<String> items = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i++) {
            items.add(pictureList.get(i).getPictureUrl());
        }
        bigImgAdapter = new ImgPreviewVPAdapter(getContext(), getDLPluginPackage(), mImgBig, items, originBitmap);
        bigImgAdapter.setiPreviewPresenter(this);
        bigImgAdapter.setOriginItem(originIndex);
        mImgBig.setAdapter(bigImgAdapter);
        mImgBig.setCurrentItem(originIndex, false);

        mWalaImgBig.setVisibility(View.VISIBLE);
        mWalaImgBig.setImageBitmap(originBitmap);

        final int fromWidth = originPicture.viewWidth;
        final int fromHeight = originPicture.viewHeight;
        final int fromX = originPicture.viewLeft;
        final int fromY = originPicture.viewTop;
        int screenWidth = SysUtil.getScreenWidth(getContext());
        int screenHeight = SysUtil.getScreenHeight(getContext());
        int animToWidth = screenWidth;
        int animToHeight = 0;
        if (hwScale > 0.001f) {
            animToHeight = (int) (animToWidth * hwScale);
            animToHeight = animToHeight > screenHeight ? screenHeight : animToHeight;
            animToWidth = (int) (animToHeight / hwScale);
        } else {
            animToHeight = screenHeight;
        }
        final int toWidth = animToWidth;
        final int toHeight = animToHeight;
        final int toX = (screenWidth - toWidth) / 2;
        final int toY = (screenHeight - toHeight) / 2;
        final ValueAnimator anim = ValueAnimator.ofFloat(0.0F, 1.0F).setDuration(ANIM_DELAY);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                int width = (int) (fromWidth + (toWidth - fromWidth) * cVal);
                int height = (int) (fromHeight + (toHeight - fromHeight) * cVal);
                int X = (int) (fromX + (toX - fromX) * cVal);
                int Y = (int) (fromY + (toY - fromY) * cVal);

                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mWalaImgBig.getLayoutParams();
                lp.width = width;
                lp.height = height;
                mWalaImgBig.setLayoutParams(lp);
                mWalaImgBig.setX(X);
                mWalaImgBig.setY(Y);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //TODO show toollayout
                updatePictureDetail(pictureList.get(originIndex));
            }
        });
        anim.start();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (anim.isRunning()) {
                    anim.cancel();
                }
                mImgBig.setVisibility(View.VISIBLE);
                mWalaImgBig.setVisibility(View.GONE);
                animOn = false;
            }
        }, ANIM_DELAY);

        Animation alphaIn = new AlphaAnimation(0, 1.0f);
        alphaIn.setDuration(ANIM_DELAY);
        mMask.setVisibility(View.VISIBLE);
        mMask.startAnimation(alphaIn);

        ObjectAnimator.ofFloat(mToolTop,"alpha",0f,1f).setDuration(ANIM_DELAY).start();
        ObjectAnimator.ofFloat(mToolBottom,"alpha",0f,1f).setDuration(ANIM_DELAY).start();
    }

    protected void BigOut(){
        if (animOn)  return;
        animOn = true;
        if (pictureList == null || pictureList.size() == 0) {
            animOn = false;
            alphaHide();
            return;
        }
        int index = mImgBig.getCurrentItem();
        ViewPicture toRect = pictureList.get(index);

        if(toRect.viewHeight == 0 || toRect.viewWidth == 0) {
            animOn = false;
            alphaHide();
            return;
        }

        float hwScale = 0.0f;
        if (toRect.getWidth() != 0) {
            hwScale = (float) toRect.getHeight() / (float) toRect.getWidth();
        }
        if (hwScale < 0.001f) {
            animOn = false;
            alphaHide();
            return;
        }

        final int toWidth = toRect.viewWidth;
        final int toHeight = toRect.viewHeight;
        final int toX = toRect.viewLeft;
        final int toY = toRect.viewTop;
        int screenHeight = SysUtil.getScreenHeight(getContext());
        int screenWidth = SysUtil.getScreenWidth(getContext());

        int animFromWidth = screenWidth;
        int animFromHeight = 0;
        if (hwScale != 0) {
            animFromHeight = (int) (animFromWidth*hwScale);
            animFromHeight = animFromHeight > screenHeight ? screenHeight : animFromHeight;
            animFromWidth = (int) (animFromHeight/hwScale);
        }else {
            animFromHeight = screenHeight;
        }

        Rect rect = getCurrentImageRect(animFromWidth,animFromHeight);
        final int fromWidth = rect.width();
        final int fromHeight = rect.height();
        final int fromX = (screenWidth - fromWidth)/2;
        final int fromY = (screenHeight - fromHeight)/2;

        Bitmap screenshot = Bitmap.createBitmap(fromWidth, fromHeight, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(screenshot);
        c.translate(-mImgBig.getScrollX()-fromX, -mImgBig.getScrollY()-fromY);
        mImgBig.draw(c);
        mWalaImgBig.setVisibility(View.VISIBLE);
        mWalaImgBig.setImageBitmap(screenshot);

        mImgBig.setVisibility(View.GONE);

        final ValueAnimator anim = ValueAnimator.ofFloat(0.0F, 1.0F).setDuration(ANIM_DELAY);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                int width = (int) (fromWidth + (toWidth - fromWidth) * cVal);
                int height = (int) (fromHeight + (toHeight - fromHeight) * cVal);
                int X = (int) (fromX + (toX - fromX) * cVal);
                int Y = (int) (fromY + (toY - fromY) * cVal);

                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mWalaImgBig.getLayoutParams();
                lp.width = width;
                lp.height = height;
                mWalaImgBig.setLayoutParams(lp);
                mWalaImgBig.setX(X);
                mWalaImgBig.setY(Y);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                //TODO hide toollayout
            }
        });
        anim.start();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (anim.isRunning()) {
                    anim.cancel();
                }
                animOn = false;
                mWalaImgBig.setVisibility(View.GONE);
                mImgBig.setVisibility(View.GONE);
                mMask.setVisibility(View.GONE);
                onDestroy();
            }
        }, ANIM_DELAY);
        Animation alphaOut = new AlphaAnimation(1.0f, 0);
        alphaOut.setDuration(ANIM_DELAY);
        mMask.startAnimation(alphaOut);

        ObjectAnimator.ofFloat(mToolTop,"alpha",1f,0f).setDuration(ANIM_DELAY).start();
        ObjectAnimator.ofFloat(mToolBottom,"alpha",1f,0f).setDuration(ANIM_DELAY).start();
    }

    protected void alphaHide(){
        ObjectAnimator animAlpha = ObjectAnimator.ofFloat(root,"alpha",1f,0f).setDuration(ANIM_DELAY);
        ObjectAnimator animScaleX = ObjectAnimator.ofFloat(root,"scaleX",1.0f,0.8f).setDuration(ANIM_DELAY);
        ObjectAnimator animScaleY = ObjectAnimator.ofFloat(root,"scaleY",1.0f,0.8f).setDuration(ANIM_DELAY);
        ObjectAnimator animAlpha2 = ObjectAnimator.ofFloat(mToolTop,"alpha",1f,0f).setDuration(ANIM_DELAY);
        ObjectAnimator animAlpha3 = ObjectAnimator.ofFloat(mToolBottom,"alpha",1f,0f).setDuration(ANIM_DELAY);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animAlpha, animScaleX, animScaleY, animAlpha2, animAlpha3);
        set.setDuration(ANIM_DELAY);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animOn = false;
                mWalaImgBig.setVisibility(View.GONE);
                mImgBig.setVisibility(View.GONE);
                mMask.setVisibility(View.GONE);

                root.setVisibility(View.GONE);
                root.setAlpha(1f);
                root.setScaleX(1f);
                root.setScaleY(1f);
                mToolTop.setAlpha(1f);

                onDestroy();
            }
        });
        set.start();
    }

    protected void alphaShow(){
        animOn = false;
        if (pictureList == null){
            pictureList = new ArrayList<>();
            ViewPicture vp = new ViewPicture();
            vp.setPictureUrl("default_url");
            pictureList.add(vp);
        }
        List<String> items = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i++) {
            items.add(pictureList.get(i).getPictureUrl());
        }
        bigImgAdapter = new ImgPreviewVPAdapter(getContext(), getDLPluginPackage(), mImgBig, items, originBitmap);
        bigImgAdapter.setiPreviewPresenter(this);
        bigImgAdapter.setOriginItem(originIndex);
        mImgBig.setAdapter(bigImgAdapter);
        mImgBig.setCurrentItem(originIndex, false);

        mWalaImgBig.setVisibility(View.GONE);
        mImgBig.setVisibility(View.VISIBLE);
        mMask.setVisibility(View.VISIBLE);

        ObjectAnimator.ofFloat(root,"alpha",0f,1f).setDuration(ANIM_DELAY).start();
        ObjectAnimator.ofFloat(root,"scaleX",0.8f,1f).setDuration(ANIM_DELAY).start();
        ObjectAnimator.ofFloat(root,"scaleY",0.8f,1f).setDuration(ANIM_DELAY).start();

        ObjectAnimator.ofFloat(mToolTop,"alpha",0f,1f).setDuration(ANIM_DELAY).start();
        ObjectAnimator.ofFloat(mToolBottom,"alpha",0f,1f).setDuration(ANIM_DELAY).start();
    }

    public String getCurrentUrl(){
        if (bigImgAdapter != null) {
            return bigImgAdapter.getCurrentUrl();
        }else {
            return null;
        }
    }

    public void onDestroy() {
        originBitmap = null;
        setVisibility(GONE);
        if(mPictureDetailPresenter != null)
            mPictureDetailPresenter.onDestroy();
    }

    @Override
    public void savePic(String url) {
        if(shouldRequestPermission())
            return;
        ImgPreviewHelper.savePic(getContext(), url);
    }

    @Override
    public void showSavePicDialog() {
    }

    public void savePic() {
        if (bigImgAdapter != null) {
            bigImgAdapter.savePicture();
        }
    }

    @Override
    public void animOut() {
        if(mPictureDetailPresenter.onBackpressed())
            return;
        BigOut();
    }

    @Override
    public boolean canLongClick() {
        return false;
    }

    private Rect getCurrentImageRect(int width,int height){
        Rect rect = new Rect(0,0,width,height);
        Object fragment = bigImgAdapter.instantiateItem(mImgBig,mImgBig.getCurrentItem());
        if (fragment != null && fragment instanceof ViewPagerLayout){
            Rect fr = ((ViewPagerLayout)fragment).getCurrentImageRect();
            if (fr != null && fr.width() > 0 && fr.width() < rect.width() && fr.height() > 0 && fr.height() < rect.height()){
                return fr;
            }
        }
        return rect;
    }

    private void startShare(String url, final boolean isTimeline) {
        String localPath = getLocalPath(url);

        if(shouldRequestPermission())
            return;
//        localPath = Utils.copyToFile(localPath);
//
//        ShareModule shareModule = new ShareModule();
//        shareModule.mShareChannel = isTimeline ? ShareType.TIMELINE : ShareType.WECHAT;
//        shareModule.WeiXinTpye = ShareModule.TYPE_IMG;
//
//        if(StringUtils.isBlank(localPath)) {
//            Utils.showToast(context, "分享内容无效");
//        } else {
//            shareModule.imagePath = localPath;
//            if(mBridge != null)
//                mBridge.doShare(shareModule);
//        }
        if(StringUtils.isBlank(localPath)) {
            Utils.showToast(context, "分享内容无效");
            return;
        }
        try {
            Luban.get(getContext()).load(new File(localPath)).putGear(Luban.THIRD_GEAR).setCompressListener(new OnCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String dest) {
                    if(StringUtils.isBlank(dest)) {
                        Utils.showToast(context, "文件不存在");
                        return;
                    } else if("ERROR".equalsIgnoreCase(dest)) {
                        Utils.showToast(context, "文件文法访问,请先在应用程序设置中打开存储权限");
                        return;
                    }
                    Utils.sysout("wechat share pic:" + dest);

                    ShareModule shareModule = new ShareModule();
                    shareModule.mShareChannel = isTimeline ? ShareType.TIMELINE : ShareType.WECHAT;
                    shareModule.WeiXinTpye = ShareModule.TYPE_IMG;
                    shareModule.imagePath = dest;
                    if(mBridge != null)
                        mBridge.doShare(shareModule);
                }

                @Override
                public void onError() {
                    Utils.showToast(context, "文件压缩失败");
                }
            }).launch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void manageShareLayout(final boolean show) {
        ValueAnimator anim = ValueAnimator.ofFloat(show ? 0 : 1, show ? 1 : 0);
        anim.setDuration(400);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                mShareLayout.setAlpha(value);
                mShareWechat.setAlpha(value);
                mShareWeibo.setAlpha(value);
                mShareTimeline.setAlpha(value);

                if(show) {
                    float translationY = mShareWechat.getHeight() * (1-value);
                    mShareWechat.setTranslationY(translationY);
                    mShareWeibo.setTranslationY(translationY);
                    mShareTimeline.setTranslationY(translationY);
                }
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!show) {
                    mShareLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                if(show) {
                    mShareLayout.setAlpha(0f);
                    mShareWechat.setAlpha(0f);
                    mShareWeibo.setAlpha(0f);
                    mShareTimeline.setAlpha(0f);
                    mShareLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        anim.start();
    }

    private void shareByWeibo() {
        String url = getCurrentUrl();
        String localPath = getLocalPath(url);

        AppShare appShare = UserUtil.getAppShare();

        if(appShare == null) {
            return;
        }

        if(StringUtils.isBlank(localPath)) {
            Utils.showToast(context, "分享内容无效");
        } else {
            shareImg(localPath, appShare.weiboPicContent);
        }
    }

    private void shareImg(String path, final String content) {
        try {
            if(shouldRequestPermission())
                return;
            Luban.get(getContext()).load(new File(path)).putGear(Luban.THIRD_GEAR).setCompressListener(new OnCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String dest) {
                    if(StringUtils.isBlank(dest)) {
                        Utils.showToast(context, "文件不存在");
                        return;
                    } else if("ERROR".equalsIgnoreCase(dest)) {
                        Utils.showToast(context, "文件文法访问,请先在应用程序设置中打开存储权限");
                        return;
                    }
                    Utils.sysout("weibo share pic:" + dest);
                    ShareModule shareModule = new ShareModule();
                    shareModule.imagePath = dest;
                    shareModule.content = content;
                    WeiboUtil.getInstance((Activity) context).startShareImg((Activity) context, shareModule);
                }

                @Override
                public void onError() {
                    Utils.showToast(context, "文件压缩失败");
                }
            }).launch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Checks whether it is necessary to ask for permission to read storage. If necessary, it also
     * requests permission.
     *
     * @return true if a permission request is made. False if it is not necessary.
     */
    @TargetApi(23)
    private boolean shouldRequestPermission() {
        if (requiresPermission()) {
            ((Activity) context).requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            Utils.showToast(context, "文件文法访问,请先在应用程序设置中打开存储权限");
            return true;
        } else {
            return false;
        }
    }

    @TargetApi(23)
    private boolean requiresPermission() {
        return StorageUtil.SDK_INT >= 23
                && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;
    }

    public String getLocalPath(String url) {
        Utils.sysout("current share pic path:" + url);
        if(StringUtils.isNotBlank(url))
            return url;
        return null;
    }

    @Override
    public void notifyAnim(int i) {

    }

    @Override
    public void registToManager(IPositionManager iPositionManager) {

    }

    @Override
    public void unreistFromManager(IPositionManager iPositionManager) {

    }

    @Override
    public int[] getLocations() {
        return new int[0];
    }

    @Override
    public boolean onKeyDownEvent(int keyCode, KeyEvent keyEvent) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(getVisibility() == VISIBLE) {
                if(dismissLayout())
                    return true;
                if(mPictureDetailPresenter.onBackpressed())
                    return true;
                if(mShareLayout.getVisibility() == View.VISIBLE) {
                    manageShareLayout(false);
                    return true;
                }
                BigOut();
                return true;
            }
        }
        return false;
    }

    public interface OnLoadMoreListener {
        public void shouldLoadMore();
    }

}
